<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      style="background: white;margin-bottom: 8px;padding-top: 20px"
    >
      <el-form-item label="任务名称" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入任务名称"
          clearable
          style="width: 160px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务组名" prop="jobGroup">
        <el-select
          v-model="queryParams.jobGroup"
          placeholder="请选择任务组名"
          clearable
          style="width: 160px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in $dict.job_group"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行状态" prop="executeStatus">
        <el-select
          v-model="queryParams.executeStatus"
          placeholder="请选择执行状态"
          clearable
          style="width: 180px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in $dict.common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="content-box">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-has-perm="['system:job:delete']"
            type="danger"
            plain
            :icon="Delete"
            size="small"
            :disabled="multiple"
            @click="handleDelete"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-has-perm="['system:job:delete']"
            type="danger"
            plain
            :icon="Delete"
            size="small"
            @click="handleClean"
          >清空
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-has-perm="['system:job:export']"
            type="warning"
            plain
            :icon="Download"
            size="small"
            @click="handleExport"
          >导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            :icon="Close"
            size="small"
            @click="handleClose"
          >关闭
          </el-button>
        </el-col>
        <div style="flex: 1" />
        <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
      </el-row>

      <el-table v-loading="loading" :data="jobLogList" @selection-change="handleSelectionChange" height="100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="日志编号" width="80" align="center" prop="id" />
        <el-table-column label="任务名称" align="center" prop="jobName" :show-overflow-tooltip="true" />
        <el-table-column label="任务组名" align="center" prop="jobGroup" :show-overflow-tooltip="true">
          <template #default="scope">
            <dict-tag :options="$dict.job_group" :value="scope.row.jobGroup" />
          </template>
        </el-table-column>
        <el-table-column label="调用目标字符串" align="center" prop="invokeTarget" :show-overflow-tooltip="true" />
        <el-table-column label="日志信息" align="center" prop="jobMessage" :show-overflow-tooltip="true" />
        <el-table-column label="执行状态" align="center" prop="executeStatus">
          <template #default="scope">
            <dict-tag :options="$dict.common_status" :value="scope.row.executeStatus" />
          </template>
        </el-table-column>
        <el-table-column label="执行时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              v-has-perm="['system:job:query']"
              size="small"
              link
              :icon="View"
              @click="handleView(scope.row)"
            >详细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="flex: 1" />
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 调度日志详细 -->
    <el-dialog title="调度日志详细" v-model="open" width="700px" append-to-body>
      <el-form ref="formRef" :model="form" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="日志序号：">{{ form.id }}</el-form-item>
            <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{ form.jobGroup }}</el-form-item>
            <el-form-item label="执行时间：">{{ form.createTime }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用方法：">{{ form.invokeTarget }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日志信息：">{{ form.jobMessage }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行状态：">
              <div v-if="form.executeStatus === '0'">正常</div>
              <div v-else-if="form.executeStatus === '1'">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="form.executeStatus === 1" label="异常信息：">{{ form.exceptionInfo }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {View, Close, Delete, Download, Refresh, Search} from '@element-plus/icons-vue'
import {parseTime} from "@/utils/index.js"
import * as utils from "@/utils/index.js"
import tab from "@/plugins/tab.js"

const route = useRoute()


// 响应式数据
const loading = ref(true)
const ids = ref([])
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const jobLogList = ref([])
const open = ref(false)
const dateRange = ref([])
const form = ref({})
const queryForm = ref(null)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  jobName: undefined,
  jobGroup: undefined,
  executeStatus: undefined
})

// 初始化数据
onMounted(() => {
  const jobId = route.query.jobId
  if (jobId !== undefined && jobId !== 0) {
    $xl.apis.getJob({
      jointUrl: '/' + jobId
    }).then(response => {
      queryParams.jobName = response.data?.jobName
      queryParams.jobGroup = response.data?.jobGroup
      getList()
    })
  } else {
    getList()
  }
})

// 方法
const getList = () => {
  loading.value = true
  $xl.apis.getJobLogs({
    params: utils.addDateRange(queryParams, dateRange.value)
  }).then(res => {
    jobLogList.value = res.data.records
    total.value = res.data.total
  }).catch(err => {
    console.log(err)
  }).finally(() => {
    loading.value = false
  })
}

const handleClose = () => {
  const obj = {path: '/system/job'}
  tab.closeOpenPage(obj)
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  dateRange.value = []
  queryForm.value?.resetFields()
  handleQuery()
}

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

const handleView = (row) => {
  open.value = true
  form.value = row
}

const handleDelete = () => {
  $xl.modal.confirm(`是否确认删除调度日志编号为"${ids.value}"的数据项？`).then(() => {
    $xl.apis.deleteJobLog({
      jointUrl: '/' + ids.value
    }).then(() => {
      getList()
      $xl.modal.msgSuccess('删除成功')
    })
  })
}

const handleClean = () => {
  $xl.modal.confirm('是否确认清空所有调度日志数据项？').then(() => {
    $xl.apis.cleanJobLog().then(res => {
      getList()
      $xl.modal.msgSuccess('清空成功')
    })
  })
}

const handleExport = () => {
  $xl.apis.download('/system/log/export', {
    ...queryParams
  }, `jobLog_${new Date().getTime()}.xlsx`)
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  font-weight: bolder;
}

.content-box {
  overflow-y: auto;
  background: #ffffff;
  padding: 20px 20px 15px;
  border-radius: 5px;
  flex: 1;
  display: flex;
  flex-direction: column;

  :deep(.el-scrollbar__wrap) {
    overflow-x: hidden;
  }
}
</style>
